import techAlertApi from '@/service/api'
import dayjs from 'dayjs'
import React, { useContext, useEffect, useRef, useState } from 'react'
import { LOOP_TIME_MIL } from '@/config/env'
interface GlobalContextType {
  businessSummary: number
  businessDisposedSum: number
  maintenanceSummary: number
  maintenanceDisposedSum: number
  isUpdate: boolean
  isLoop: boolean
  startAudio: boolean
  setIsUpdate: React.Dispatch<React.SetStateAction<boolean>>
  setIsLoop: React.Dispatch<React.SetStateAction<boolean>>
  setStartAudio: React.Dispatch<React.SetStateAction<boolean>>
}

const GlobalContext = React.createContext<GlobalContextType | null>(null)

export const useGlobalContext = (): GlobalContextType => {
  const context = useContext(GlobalContext)
  if (!context) {
    throw new Error('useGlobalContext must be used within a GlobalProvider')
  }
  return context
}

export const GlobalProvider = ({
  children,
}: {
  children?: React.ReactNode
}) => {
  const [businessSummary, setBusinessSummary] = useState(0)
  const [businessDisposedSum, setBusinessDisposedSum] = useState(0)
  const [maintenanceSummary, setMaintenanceSummary] = useState(0)
  const [maintenanceDisposedSum, setMaintenanceDisposedSum] = useState(0)
  const [isUpdate, setIsUpdate] = useState(false)
  const [isLoop, setIsLoop] = useState(true)
  const [startAudio, setStartAudio] = useState(false)
  const timer = useRef<NodeJS.Timeout | null>(null)
  const playAudio = useRef(false)
  useEffect(() => {
    //todo 如果有未处理业务或者未处理工单数量改变并且大于0，则说明有新的数据，则通知更新
    if (businessSummary > 0 || maintenanceDisposedSum > 0) {
      setIsUpdate(true)
    }
  }, [businessSummary, maintenanceDisposedSum])

  useEffect(() => {
    getAlertSummary()
    return () => {
      if (timer.current) {
        clearInterval(timer.current)
      }
    }
  }, [])

  useEffect(() => {
    if (isLoop) {
      timer.current = setInterval(async () => {
        await getAlertSummary()
        if (playAudio.current) {
          setStartAudio(true)
        }
      }, LOOP_TIME_MIL)
    } else {
      timer.current && clearInterval(timer.current)
    }
  }, [isLoop])

  async function getAlertSummary() {
    const queryStartTime = dayjs().format('YYYY-MM-DD 00:00:00')
    const queryEndTime = dayjs().format('YYYY-MM-DD 23:59:59')
    playAudio.current = false
    const [businessRes, maintenanceRes] = await Promise.allSettled([
      techAlertApi.alertSummary({
        bizType: 0,
        queryStartTime,
        queryEndTime,
      }),
      techAlertApi.alertSummary({
        bizType: 1,
        queryStartTime,
        queryEndTime,
      }),
    ])

    if (businessRes.status === 'fulfilled' && businessRes.value.code === 200) {
      if (businessRes.value.data.amount > businessSummary) {
        playAudio.current = true
      }
      setBusinessSummary(businessRes.value.data.amount)
      const disposedSum =
        businessRes.value.data.missedAmount +
        businessRes.value.data.receivedAmount
      setBusinessDisposedSum(disposedSum)
    }
    if (
      maintenanceRes.status === 'fulfilled' &&
      maintenanceRes.value.code === 200
    ) {
      if (
        !playAudio.current &&
        maintenanceRes.value.data.amount > maintenanceSummary
      ) {
        playAudio.current = true
      }
      setMaintenanceSummary(maintenanceRes.value.data.amount)
      const disposedSum =
        maintenanceRes.value.data.missedAmount +
        maintenanceRes.value.data.receivedAmount
      setMaintenanceDisposedSum(disposedSum)
    }
  }
  return (
    <GlobalContext.Provider
      value={{
        businessSummary,
        businessDisposedSum,
        maintenanceSummary,
        maintenanceDisposedSum,
        isUpdate,
        isLoop,
        startAudio,
        setIsUpdate,
        setIsLoop,
        setStartAudio,
      }}
    >
      {children}
    </GlobalContext.Provider>
  )
}
